// var that;
'use strict'
class Tab {
    constructor(id) {
        // that = this;
        this.min = document.querySelector(id)
        this.add = this.min.querySelector('.tabadd')
        this.ul = this.min.querySelector(".fisrstnav ul")
        this.tabscon = this.min.querySelector('.tabscon')
        this.init()
    }
    init() {
        this.doneTab()
        for (var i = 0; i < this.lis.length; i++) {
            this.lis[i].index = i
            this.lis[i].onclick = this.toggleTab.bind(this.lis[i], this);
            this.remove[i].onclick = this.removeTab.bind(this.remove[i], this);
            this.span[i].ondblclick = this.eatiTab;
            this.section[i].ondblclick = this.eatiTab;
        }
        this.add.onclick = this.addTab.bind(this.lis[i], this);

    }
    doneTab() {
        this.span = this.min.querySelectorAll(".fisrstnav li span:first-child")
        this.lis = this.min.querySelectorAll('li')
        this.remove = this.min.querySelectorAll('.icon-guanbi');
        this.section = this.min.querySelectorAll('section')
    }
    // 切换功能

    toggleTab(that) {
        that.totop()
        this.className = "liactive";
        that.section[this.index].className = 'conactive';
    }
    totop() {
        for (var i = 0; i < this.lis.length; i++) {
            this.lis[i].className = ''
            this.section[i].className = ''
        }
    }
    // 添加功能
    addTab(that) {
        that.totop()
        var random = Math.random();
        var li = '<li class="liactive"><span>测试1</span><span class="iconfont icon-guanbi"></span></li>'
        var section = '<section class="conactive">测试' + random + '</section>'
        that.ul.insertAdjacentHTML('beforeend', li)
        that.tabscon.insertAdjacentHTML('beforeend', section)
        that.init()
    }
    // 消除功能
    removeTab(that, e) {
        e.stopPropagation()
        var index = this.parentNode.index
        console.log(index);
        that.lis[index].remove()
        that.section[index].remove()
        that.init()
        if (document.querySelector(".liactive")) return
        index--;
        // if (index <= 0) {
        //     index == that.lis.length
        // }
        that.lis[index] && that.lis[index].click();
    }
    // 修改功能
    eatiTab() {
        // 双击禁止选定文字
        window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
        var text = this.innerHTML;
        // console.log(text);
        this.innerHTML = `<input type='text' value=${text} />`;
        var inputElemt = this.children[0];
        inputElemt.select()
        inputElemt.onblur = function () {
            this.parentNode.innerHTML = this.value;
        };
        inputElemt.onkeyup = function (e) {
            if (e.keyCode === 13) {
                inputElemt.blur();
            }
        }
    }
}
new Tab("#tab");